#include "DataCollector.h"
#include <sstream>
#include <iomanip>
#include <stdexcept>
#include "include/nlohmann/json.hpp"
#include "SecurityAuditor.h"

// 数据采集器构造函数
DataCollector::DataCollector(std::chrono::milliseconds interval)
    : isRunning(false), collectionInterval(interval), totalPoints(0) {
    // 初始化安全审计器
    securityAuditor = std::make_unique<SecurityAuditor>("/Users/hefeiyu/Downloads/智慧电厂SIS系统/config/security_config.json");
    if (securityAuditor->initialize()) {
        securityAuditor->logEvent(AuditEventType::SYSTEM_EVENT, "system", "数据采集器初始化成功");
    } else {
        std::cerr << "安全审计器初始化失败" << std::endl;
    }
}

// 数据采集器析构函数
DataCollector::~DataCollector() {
    stopCollection();
    if (securityAuditor && securityAuditor->enabled()) {
        securityAuditor->logEvent(AuditEventType::SYSTEM_EVENT, "system", "数据采集器已关闭");
    }
}

// 添加协议处理器
bool DataCollector::addProtocolHandler(std::unique_ptr<ProtocolHandler> handler) {
    if (!handler) return false;
    if (!handler->connect("")) { // 这里需要实际配置
        std::cerr << "Failed to connect with protocol: " << handler->getProtocolName() << std::endl;
        return false;
    }
    handlers.push_back(std::move(handler));
    return true;
}

// 启动数据采集
bool DataCollector::startCollection() {
    if (isRunning) return true;
    if (handlers.empty()) {
        std::cerr << "No protocol handlers added!" << std::endl;
        if (securityAuditor && securityAuditor->enabled()) {
            securityAuditor->logEvent(AuditEventType::SYSTEM_EVENT, "system", "启动失败: 未添加协议处理器");
        }
        return false;
    }

    isRunning = true;
    collectionThread = std::thread(&DataCollector::collectDataLoop, this);
    
    if (securityAuditor && securityAuditor->enabled()) {
        securityAuditor->logEvent(AuditEventType::SYSTEM_EVENT, "system", "数据采集已启动");
    }
    return true;
}

// 停止数据采集
void DataCollector::stopCollection() {
    if (!isRunning) return;

    isRunning = false;
    if (collectionThread.joinable()) {
        collectionThread.join();
    }

    // 断开所有协议连接
    for (auto& handler : handlers) {
        handler->disconnect();
    }
    
    if (securityAuditor && securityAuditor->enabled()) {
        securityAuditor->logEvent(AuditEventType::SYSTEM_EVENT, "system", "数据采集已停止");
    }
}

// 设置数据回调函数
void DataCollector::setDataCallback(std::function<void(const std::vector<PointData>&)> callback) {
    dataCallback = callback;
}

// 获取所有测点数据
std::vector<PointData> DataCollector::getAllPoints() {
    std::lock_guard<std::mutex> lock(dataMutex);
    
    if (securityAuditor && securityAuditor->enabled()) {
        securityAuditor->logEvent(AuditEventType::DATA_ACCESS, "system", "获取所有测点数据");
    }
    
    std::vector<PointData> result;
    for (const auto& pair : pointDatabase) {
        result.push_back(pair.second);
    }
    return result;
}

// 检查告警阈值
void DataCollector::checkAlarmThresholds(PointData& point) {
    bool previouslyInAlarm = point.is_alarm;
    
    if (point.value > point.upper_limit || point.value < point.lower_limit) {
        point.is_alarm = true;
        // 新告警产生
        if (!previouslyInAlarm && securityAuditor && securityAuditor->enabled()) {
            securityAuditor->logEvent(AuditEventType::ALARM_TRIGGERED, "system", 
                "测点告警: " + point.name + " (ID: " + point.id + "), 值: " + std::to_string(point.value));
        }
    } else {
        // 告警清除
        if (previouslyInAlarm && securityAuditor && securityAuditor->enabled()) {
            securityAuditor->logEvent(AuditEventType::ALARM_CLEARED, "system", 
                "测点告警清除: " + point.name + " (ID: " + point.id + "), 当前值: " + std::to_string(point.value));
        }
        point.is_alarm = false;
    }
}

// 数据采集循环
void DataCollector::collectDataLoop() {
    while (isRunning) {
        auto startTime = std::chrono::high_resolution_clock::now();
        std::vector<PointData> allNewData;

        // 从所有协议处理器读取数据
        for (const auto& handler : handlers) {
            try {
                std::vector<PointData> newData = handler->readData();
                allNewData.insert(allNewData.end(), newData.begin(), newData.end());
            } catch (const std::exception& e) {
                std::cerr << "Error reading data from " << handler->getProtocolName() << ": " << e.what() << std::endl;
            }
        }

        // 处理新数据
        if (!allNewData.empty()) {
            std::lock_guard<std::mutex> lock(dataMutex);
            for (auto& data : allNewData) {
                data.timestamp = std::chrono::system_clock::now();
                checkAlarmThresholds(data);
                pointDatabase[data.id] = data;
            }
            totalPoints = pointDatabase.size();

            // 如果设置了回调函数，调用它
            if (dataCallback) {
                dataCallback(allNewData);
            }
        }

        // 控制采集频率
        auto endTime = std::chrono::high_resolution_clock::now();
        auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime);
        auto sleepTime = collectionInterval - elapsed;

        if (sleepTime > std::chrono::milliseconds(0)) {
            std::this_thread::sleep_for(sleepTime);
        }
    }
}

// 获取状态信息
std::string DataCollector::getStatusInfo() const {
    std::stringstream ss;
    ss << "Data Collector Status:\n";
    ss << "Running: " << (isRunning ? "Yes" : "No") << "\n";
    ss << "Total points: " << totalPoints << "\n";
    ss << "Collection interval: " << collectionInterval.count() << "ms\n";
    ss << "Protocol handlers: " << handlers.size() << "\n";

    for (size_t i = 0; i < handlers.size(); ++i) {
        ss << "  Handler " << (i+1) << ": " << handlers[i]->getProtocolName() << "\n";
    }

    return ss.str();
}